package xhwl.hmo.mall.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;

import com.trello.rxlifecycle.components.RxActivity;
import com.trello.rxlifecycle.components.support.RxFragment;
import com.trello.rxlifecycle.components.support.RxFragmentActivity;

import java.io.File;

import de.greenrobot.event.EventBus;
import xhwl.hmo.mall.MyApp;
import xhwl.hmo.mall.db.UpgradeDao;
import xhwl.hmo.mall.db.bean.Upgrade;
import xhwl.hmo.mall.event.UpgradeEvent;
import xhwl.hmo.mall.http.api.CheckUpgradeApi;
import xhwl.hmo.mall.http.bean.resp.UpgradeResp;
import xhwl.hmo.mall.services.UpgradeService;

import xhwl.retrofitrx.BaseApi;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * 升级管理类
 *
 * @author lim
 * @version 1.0
 * @date 2017年2月9日
 */
public class UpgradeMgr {
    public static final String apkSavePath = Environment.getExternalStorageDirectory().getPath();
    private Context mContext;
    /**
     * 检查新版本，下载、安装
     *
     * @param activity
     */
    public  void checkVersion(final RxActivity activity) {
        mContext=activity;
        CheckUpgradeApi api = new CheckUpgradeApi();
        HttpManager.getInstance().dealHttp(activity, api,listener );
    }
    public  void checkVersion(final RxFragmentActivity activity) {
        mContext=activity;
        CheckUpgradeApi api = new CheckUpgradeApi();
        HttpManager.getInstance().dealHttp(activity, api,listener );
    }
    public  void checkVersion(final RxFragment fragment) {
        mContext=fragment.getContext();
        CheckUpgradeApi api = new CheckUpgradeApi();
        HttpManager.getInstance().dealHttp(fragment, api,listener );
    }
    private OnNextListener listener=new OnNextListener<UpgradeResp>() {
        @Override
        public void onNext(UpgradeResp resp) {
            try {
                UpgradeDao upgradeDao = new UpgradeDao(mContext);
                Upgrade upgrade = upgradeDao.find(resp.VERSION_CODE);

                int curVersionCode = AppUtil.getVersionCode(mContext);
                if (curVersionCode < Integer.parseInt(resp.VERSION_CODE)) {
                    if (upgrade.getId() > 0) {//已完成下载
                        final String filePath = apkSavePath + File.separator + upgrade.getSave_path();
                        File file = new File(filePath);
                        boolean fileExist = file != null && file.exists();
                        if (fileExist) {
                            final boolean forceUpdate="1".equals(resp.FORCE_FLAG);
                            AlertDialog builder = new AlertDialog.Builder(mContext)
                                    .setMessage("是否安装新版本？")
                                    .setPositiveButton("去安装", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                            install(filePath);
                                        }
                                    }).setNegativeButton(forceUpdate?"退出":"取消", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if(forceUpdate){
                                                MyApp.getInstance().exit();
                                            }
                                            else
                                            {
                                                dialog.dismiss();
                                            }

                                        }
                                    }).create();
                            builder.setCancelable(!forceUpdate);
                            builder.setCanceledOnTouchOutside(!forceUpdate);
                            builder.show();
                        } else {
                            startDownload(BaseApi.BaseUrlYun + resp.FILE_URL, resp.VERSION_CODE, resp.CLIENT_VERSION);
                        }
                    } else {
                        startDownload(BaseApi.BaseUrlYun + resp.FILE_URL, resp.VERSION_CODE, resp.CLIENT_VERSION);
                    }
                } else {
                    EventBus.getDefault().post(new UpgradeEvent(UpgradeEvent.STATE_NEWEST));
                }
            } catch (Exception e) {
                XHLog.e("检查更新失败");
                e.printStackTrace();
            }
        }
    };
    /**
     * 打开安装界面
     *
     * @param filePath 安装包全路径
     */
    private void install(String filePath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(mContext, "xhwl.hmo.mall.fileProvider", new File(filePath));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        mContext.startActivity(intent);
    }

    /**
     * 提示用户下载，启动下载服务
     *
     * @param url
     * @param versionCode
     * @param versionName
     */
    private void startDownload(final String url, final String versionCode, final String versionName) {
        if (!AppUtil.isWifi(mContext)) {
            AlertDialog builder = new AlertDialog.Builder(mContext).setMessage("是否下载新版本？")
                    .setPositiveButton("下载", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //需要下载
                            Intent intent = new Intent(mContext, UpgradeService.class);
                            Bundle bundle = new Bundle();
                            bundle.putString(UpgradeService.EXTRA_FILE_URL, url);
                            bundle.putString(UpgradeService.EXTRA_VERSION_CODE, versionCode);
                            bundle.putString(UpgradeService.EXTRA_VERSION_NAME, versionName);
                            intent.putExtras(bundle);
                            mContext.startService(intent);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create();
            builder.show();
        } else {
            //直接下载
            Intent intent = new Intent(mContext, UpgradeService.class);
            Bundle bundle = new Bundle();
            bundle.putString(UpgradeService.EXTRA_FILE_URL, url);
            bundle.putString(UpgradeService.EXTRA_VERSION_CODE, versionCode);
            bundle.putString(UpgradeService.EXTRA_VERSION_NAME, versionName);
            intent.putExtras(bundle);
            mContext.startService(intent);
        }
    }

}
